<?php

class Adwords {
	private $_dbconn;
	private $_date;
	private $_time;
	
	public function __construct() {
		require_once "config.php";
		require_once dirname(__FILE__). '/util/connection.class.php';
		$this->_dbconn = Connection::getInstance();
		$this->_date = date('Y-m-d', time() - 60*60*24);
		$this->_time = date('YmdHis', strtotime($this->_date));
	}
	

	
	public function dumpCsv2Db($filename) {
		
		$fp = fopen($filename,'r') or die("can't open file");
		
		//exepct for  table headers
		$firstLine = true;
		while($csv_line = fgetcsv($fp)) {
			if (count($csv_line) == 5) {
				if($firstLine){
					$firstLine = false;
					continue;
				}
				else{
					$cam = $this->normalizeWords($csv_line[0]);
					$pla = $this->normalizeWords($csv_line[1]);
					$impressions = $csv_line[2];
					$landings = $csv_line[3];
					$spend = $csv_line[4];
					//except for the ones whose impression is zero and the summary line
					if(0 < $impressions && $cam != 'Total') {
						$this->saveRecords2DB($cam, $pla, $impressions, $landings, $spend);
					}
					
				}
			}			
		}
		
		fclose($fp) or die("can't close file");
		
	}
	
	private function saveRecords2DB ($cam, $pla, $impressions, $landings, $spend) {
		$sql = 'insert into site_data set cam=?, pub=?, pla=?, impression=?, landing=?,  spend=?, time_new=?';
		try {
			$this->_dbconn->execute($sql, array($cam, 'Google', $pla, $impressions, $landings, $spend, $this->_time));
		} catch (Exception $e)
		{
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
	
	private function  normalizeWords($word) {
		//'/\s/'
		//return trim(preg_replace('/[^\w]|\./', '_', $word), '[]""');
		return preg_replace('/[^\w]/', '_', $word);
	}
}

class AdwordsDownloadService {
	
	private $_clientIDs;
	private $_user;
	private $_date;
	private $_selector;
	
	public function __construct($clientIDs) {
		require_once 'Google/Api/Ads/AdWords/Lib/AdWordsUser.php';
		$this->_user = new AdWordsUser();
		$this->_date = date('Ymd', time() - 60*60*24);
		$this->_clientIDs = $clientIDs;
	}
	
	public function createReportDefinition() {
		$dirname = RAW_DATA_ROOT.'/'. date('Y_m', strtotime($this->_date));
		if (!file_exists($dirname))
		{
			mkdir($dirname, 0600, true);
		}
		
		foreach ($this->_clientIDs as $k => $id) {
			$this->_user->SetClientId($id);
			$this->_user->LogDefaults();
			
			$reoprtDefinitionService = $this->_user->GetReportDefinitionService('v201101');
			
			$selector = new Selector();
			$selector->fields = array('AdGroupName', 'KeywordText', 'Impressions', 'Clicks', 'Cost');
			$selector->dateRange = new DateRange($this->_date, $this->_date);
			
			$reportDefinition = new ReportDefinition();
			$reportDefinition->reportName = $k . "_" . date('m_d_Y', strtotime($this->_date));
			$reportDefinition->dateRangeType = 'TODAY';
			$reportDefinition->reportType = 'KEYWORDS_PERFORMANCE_REPORT';
			$reportDefinition->downloadFormat = 'CSV';
			$reportDefinition->selector = $selector;
			
			$operation = new ReportDefinitionOperation();
			$operation->operand = $reportDefinition;
			$operation->operator = 'ADD';
			
			$operations = array($operation);
			
			$result = $reoprtDefinitionService->mutate($operations);
			
			$fileName = $dirname . '/' . $k . "_" . date('m_d_Y', strtotime($this->_date));
			
			if ($result != null) {
				foreach ($result as $reportDefinition) {
					$this->downloadReport($fileName, $reportDefinition->id);
				}
			} else {
			    print "No report definitions were added.\n";
			}
		}
	}
	
	
	
	private function downloadReport($fileName, $reportId) {
		require_once 'Google/Api/Ads/AdWords/Util/ReportUtils.php';
		ReportUtils::DownloadReport($reportId, $fileName, $this->_user);
	}
	
	
}
